package MTT::Form::Access;

use HTML::FormHandler::Moose;
extends 'HTML::FormHandler::Model::DBIC';
with 'HTML::FormHandler::Render::Simple';
use namespace::autoclean;

use utf8;

use Data::Dumper;
use MTT::Libs::ObjectAccess;

has '+item_class' => ( default => 'AccessObject' );

#has '+action' => ( default => '/users/register' );

has 'name' => ( is => 'rw', default => 'permissionForm' );


has_field 'object_type' => ( type => 'Multiple', label => '', required => 1 );
has_field 'permitted' => ( type => 'Multiple', label => '', style => 'width: 130px' );
has_field 'unpermitted' => ( type => 'Multiple', label => '', style => 'width: 130px' );
has_field 'user_id' => ( type => 'Hidden' );
has_field 'submit' => ( type => 'Submit', value => 'Сохранить' );

sub options_object_type {
	my ($self) = @_;
	return unless $self->schema;

	my @options;
	foreach my $obj_type ( $self->schema->resultset('ObjectType')->all() ) {
		push @options, { value => $obj_type->id, label => $obj_type->name, note => $obj_type->descr };
	}
	return @options;
}

sub options_permitted {
	my ($self) = @_;
	return unless $self->ctx;
	
	my $sec = MTT::Libs::ObjectAccess->instance;

	my $perm_id   = $sec->permitted_objects($self->ctx, 'Оборудование');

	my @options;
	foreach my $id_switch ( @$perm_id ) {
		my $switch = $self->schema->resultset('SwitchType')->find($id_switch);
		push @options, { value => $switch->id, label => $switch->type };
	}

	return @options;
}

sub options_unpermitted {
	my ($self) = @_;
	return unless $self->ctx;
	
	my $sec = MTT::Libs::ObjectAccess->instance;

	my $unperm_id   = $sec->unpermitted_objects($self->ctx, 'Оборудование');

	my @options;
	foreach my $id_switch ( @$unperm_id ) {
		my $switch = $self->schema->resultset('SwitchType')->find($id_switch);
		push @options, { value => $switch->id, label => $switch->type };
	}

	return @options;
}


__PACKAGE__->meta->make_immutable;
1;

